/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mobiubiq.directory.client.ws;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import org.kalmeo.kuix.core.KuixConstants;
import org.mobiubiq.directory.client.Constants;
import org.mobiubiq.directory.client.KuixClient;
import org.mobiubiq.directory.client.data.Service;
import org.mobiubiq.directory.client.object.io.JSONWriter;
import org.mobiubiq.util.IOUtils;

/**
 *
 * @author Marnix Renne
 */
public class WebServiceClient {

    public static InputStream doRequest(String endpoint, String method, Object[] params) {
        return null;
    }

    public InputStream doGetRequest(Service service, WebServiceAction action) throws WebServiceException {
        HttpConnection conn = null;
        try {
            String url = buildUrl(service, action);
            conn = (HttpConnection) Connector.open(url, Connector.READ);
            if (conn.getResponseCode() != HttpConnection.HTTP_OK) {
                throw new WebServiceException(conn.getResponseCode(), conn.getResponseMessage());
            }

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(conn.openInputStream(), byteArrayOutputStream);
            conn.close();
            conn = null;

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            return byteArrayInputStream;
        } catch (EncoderException ex) {
            throw new WebServiceException("DecoderException: " + ex.getMessage());
        } catch (IOException ex) {
            throw new WebServiceException("IOException: " + ex.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                    conn = null;
                } catch (IOException e) {
                }
            }
        }
    }

    public InputStream doPostRequest(Service service, WebServiceAction action) throws WebServiceException {
        HttpConnection conn = null;
        try {
            URLCodec codec = new URLCodec();
            String url = buildUrl(service, action);
            conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
            conn.setRequestMethod(HttpConnection.POST);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream outputStream = conn.openOutputStream();
            Hashtable postParameters = action.getPostParameters();
            Enumeration keys = postParameters.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                byte[] data = (byte[]) postParameters.get(key);
                //outputStream.write((key + "=").getBytes());
                outputStream.write(data);
            }
            outputStream.close();
            if (conn.getResponseCode() != HttpConnection.HTTP_OK) {
                throw new WebServiceException(conn.getResponseCode(), conn.getResponseMessage());
            }
            // copy the response
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(conn.openInputStream(), byteArrayOutputStream);
            conn.close();
            conn = null;

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            return byteArrayInputStream;
        } catch (EncoderException ex) {
            throw new WebServiceException("EncoderException: " + ex.getMessage());
        } catch (IOException ex) {
            throw new WebServiceException("IOException: " + ex.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                    conn = null;
                } catch (IOException e) {
                }
            }
        }
    }

    private String buildUrl(Service service, WebServiceAction action) throws EncoderException {
        URLCodec codec = new URLCodec();
        JSONWriter writer = new JSONWriter();
        String endpoint = KuixClient.getDefault().getAppProperty(Constants.APP_PROPERTY_ENDPOINT);
        KuixClient.debug(endpoint, KuixConstants.ALERT_OK);

        endpoint = endpoint + Constants.APPSERVICE;
        Context context = new Context();
        StringBuffer buffer = new StringBuffer();
        buffer.append(endpoint + "?serviceId=" + service.getId());
        buffer.append("&context=" + codec.encode(writer.write(context)));
        buffer.append("&action=" + codec.encode(writer.write(action)));
        buffer.append("&objectId=" + codec.encode(service.getObject().getId()));
        return buffer.toString();
    }
}
